`include "constantes.v"

module memoria(
clk,
reset,
Bus_Data_O,	 
Bus_Data_I,
Bus_Adr,
Bus_Ctl,
Bus_ACK,
Bus_Gnt,
MemSys_ACK,
MemData_I
);

input					clk;
input					reset;
input	[`TAM_BDAT:0]	Bus_Data_O;		
input 	[`TAM_BDAT:0]	Bus_Data_I;
input	[`TAM_BADR:0]	Bus_Adr;
input	[`TAM_BCTL:0]	Bus_Ctl;
input					Bus_ACK;
input					Bus_Gnt;
output					MemSys_ACK;
output [`TAM_BDAT:0]	MemData_I;



// 2^16 = 65536
reg [`TAM_BDAT:0] Memprin [0:`TAM_MEM];
reg MemSys_ACK;
reg [`TAM_BDAT:0] MemData_I;
integer i;	 
reg inter;



initial begin
	for (i = 0; i <= `TAM_MEM; i = i + 1) begin
		Memprin[i] = i;
	end
	MemSys_ACK = 0; 
	inter = 0;
end						  

always @ (negedge reset) begin
	for (i = 0; i <= `TAM_MEM; i = i + 1) begin
		Memprin[i] = i;
	end
	MemSys_ACK = 0; 
	inter = 0;
end	
									  							 
// modificacion del bus de control
always @ (posedge clk)
begin
  if (Bus_Gnt == 1 && inter == 0) begin
  	// Escribir datos de disco
  	if (Bus_Ctl == `READ_MASK) begin
		inter = 1;
		#5 Memprin[Bus_Adr] = Bus_Data_O; 
		MemSys_ACK = 1;						
  	// Leer datos de memoria 
  	end else if (Bus_Ctl == `WRITE_MASK) begin
		inter = 1;
		#15 MemData_I = Memprin[Bus_Adr];
		MemSys_ACK = 1;					   
	end 
  end
end

// Bajar el ACK cuando el master bajar el Gnt
always @ (Bus_Gnt)
begin
	if (Bus_Gnt == 0) begin
		inter = 0;
		MemSys_ACK = 0;
	end
end

endmodule
